import subprocess
import sys
from pathlib import Path
from tkinter import Tk, filedialog, messagebox

def select_directory():
    """弹窗选择目录"""
    root = Tk()
    root.withdraw()  # 隐藏主窗口
    folder = filedialog.askdirectory(title="请选择包含 DJVU 文件的目录")
    root.destroy()
    return folder

def find_djvu_files(root_dir):
    """递归查找所有 DJVU 文件"""
    return list(Path(root_dir).rglob("*.djvu"))

def batch_convert_djvu(root_dir):
    """批量转换并保持原目录结构"""
    djvu_files = find_djvu_files(root_dir)
    if not djvu_files:
        messagebox.showwarning("无文件", "未找到任何 DJVU 文件！")
        return

    success = 0
    failed = []
    for djvu_path in djvu_files:
        try:
            # 生成输出路径（与原文件同目录）
            pdf_path = djvu_path.with_suffix(".pdf")
            # 确保输出目录存在
            pdf_path.parent.mkdir(parents=True, exist_ok=True)
            
            # 根据不同系统选择 ddjvu 路径（需根据实际安装位置修改！）
            if sys.platform.startswith("win"):
                ddjvu_bin = r"C:\Program Files (x86)\DjVuLibre\ddjvu.exe"  # Windows
            else:
                ddjvu_bin = "ddjvu"  # macOS/Linux

            # 执行转换命令
            cmd = [
                ddjvu_bin,
                "-format=pdf",
                str(djvu_path),
                str(pdf_path)
            ]
            print(f"✅ 正在转换: {djvu_path} ")
            subprocess.run(cmd, check=True, capture_output=True)
            print(f"✅ 转换成功: {pdf_path}\n")
            success += 1
        except Exception as e:
            failed.append(f"{djvu_path.name} - {str(e)}")

    # 显示结果弹窗
    result_msg = f"转换完成！\n成功: {success} 个\n失败: {len(failed)} 个"
    if failed:
        result_msg += "\n\n失败文件:\n" + "\n".join(failed)
    messagebox.showinfo("结果", result_msg)

if __name__ == "__main__":
    input_dir = select_directory()
    if input_dir:
        batch_convert_djvu(input_dir)
    else:
        messagebox.showinfo("取消", "未选择目录，程序退出。")
 